﻿using Abp.Collections.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using WebApiClient.Attributes;
using WebApiClient.Contexts;

namespace NetCore.ServiceGroup
{
    /// <summary>
    /// 默认token注入过滤器，用于将请求头中的Authorization注入到接口请求中
    /// </summary>
    public class DefaultTokenAttribute : ApiActionFilterAttribute
    {
        //private IConfigurationRoot _appConfiguration;
        //public DefaultTokenAttribute(IConfigurationRoot appConfiguration)
        //{
        //    _appConfiguration = appConfiguration;
        //}
        public override async Task OnBeginRequestAsync(ApiActionContext context)
        {
            var httpContextAccessor = context.GetService<IHttpContextAccessor>();
            var token = await httpContextAccessor.HttpContext.GetTokenAsync("Authorization");
            context.RequestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
            var tenant = httpContextAccessor.HttpContext.Request.Headers.GetOrDefault("TenantId");
            if (tenant.Any())
            {
                context.RequestMessage.Headers.Add("Tenant", tenant.ToString());
            }
            await base.OnBeginRequestAsync(context);
        }
    }
}
